package org.jks.service;

import java.io.File;
import java.util.List;

import org.jks.model.Attachment;
import org.jks.model.Flight;
import org.jks.util.OSUtil;
import org.springframework.stereotype.Service;

@Service
public class AttachmentService extends EntityService<Attachment>{
	
	public AttachmentService(){
		MODEL_NAME = Attachment.class.getSimpleName();
		CLASS_NAME = Attachment.class;
	}
	
	public boolean isExist(String name)
	{
		String hql = "from " + MODEL_NAME + " where Name='" + name + "'";
		List<Attachment> temp = super.find(hql);
		if(temp == null || temp.size() == 0)
		{
			return false;
		}
		return true;
	}
	
	/**
	 * 文件名或目录名中不要用_ \ 系统需要用
	 * @param flight
	 * @param path
	 * @return
	 */
	public List<Attachment> list(Flight flight, String path){
		String hql = "from " + MODEL_NAME;
		boolean root = false;
		if(path.equals(File.separator)){
			root = true;
		}
		if(!root){
			path = path.replace(File.separator, "_");
			path += "_";
		}
		
		if(flight == null){
			hql += " where Flight is null";
		}
		else{
			hql += " where Flight.Id="+flight.getId();
		}
		
		if(!root){
			hql += " and Path like '"+path+"%'";
			if(OSUtil.isWindows()){
				hql += " and (length(Path) - length(replace(Path,'\\\\','')) > (length('"+path+"')-length(replace('"+path+"','_',''))-1))";
				hql += " and (length(Path) - length(replace(Path,'\\\\','')) < (length('"+path+"')-length(replace('"+path+"','_',''))+1))";
			}
			else{
				hql += " and (length(Path) - length(replace(Path,'/','')) > (length('"+path+"')-length(replace('"+path+"','_',''))-1))";
				hql += " and (length(Path) - length(replace(Path,'/','')) < (length('"+path+"')-length(replace('"+path+"','_',''))+1))";
			}
		}
		else{
			if(OSUtil.isWindows()){
				hql += " and (length(Path) - length(replace(Path,'\\\\','')) = 1)";
			}
			else{
				hql += " and (length(Path) - length(replace(Path,'/','')) = 1)";
			}
		}
		return super.find(hql);
	}
	
	public void delete(Flight flight, String path){
		String hql = "delete from " + MODEL_NAME;
		boolean root = false;
		if(path.equals(File.separator)){
			root = true;
		}
		if(!root){
			path = path.replace("\\", "_");
		}
		
		if(flight == null){
			hql += " where Flight is null";
		}
		else{
			hql += " where Flight.Id="+flight.getId();
		}
		hql += " and Path like '"+path+"%'";
		super.delete(hql);
	}
	
	public List<Attachment> query(Flight flight, String path){
		String hql = "from " + MODEL_NAME;
		if(flight == null){
			hql += " where Flight is null";
		}
		else{
			hql += " where Flight.Id="+flight.getId();
		}
		hql += " and Name like '%"+path+"%'";
		return super.find(hql);
	}
}
